package com.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class UserFilter implements Filter {

    List<String> prefixIignores = new ArrayList<>();
    public void init(FilterConfig config) throws ServletException {
        //System.out.println("过滤器init...");
        String cp = config.getServletContext().getContextPath();    //  /Barbr
        String ignoresParam = config.getInitParameter("ignores");//  /login.jsp
        String[] ignoreArray = ignoresParam.split(",");
        for (String s : ignoreArray) {
            prefixIignores.add(cp +"/html"+ s);
        }
    }

    public void destroy() {
        System.out.println("过滤器destroy...");
    }

    public boolean canIgnore(HttpServletRequest request){
        String url = request.getRequestURI();
        for (String ignore : prefixIignores) {
            System.out.println("url------------->"+url);
            if (url.startsWith(ignore)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对用户权限进行管理
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //拦截请求
        //设置乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //判断当前url是否是login.jsp，是则放行否则拦截
        if (canIgnore((HttpServletRequest) request)){
            //返回true则是以login.jsp结尾的，所以放行
            chain.doFilter(request,response);
        }
        //输出

        PrintWriter out = response.getWriter();
        System.out.println("拦截了jsp页面...");
        //判断session中有无数据
        HttpSession session = ((HttpServletRequest) request).getSession();
        //获取session中所有键值
        Enumeration enumeration = session.getAttributeNames();
        if (!enumeration.hasMoreElements()){
            out.println("拒绝访问...");
            out.println("<a href='http://localhost:8080/Barbr/html/login.jsp'>前往登录</a>");
        }
        else {
            //遍历session中的键值对
           /* while (enumeration.hasMoreElements()){
                String name = enumeration.nextElement().toString();
                Object value = ((HttpServletRequest) request).getSession().getAttribute(name);
                System.out.println(name+":"+value.toString());
            }*/
            System.out.println("有session，放行...");
            //放行语句
            chain.doFilter(request, response);
        }


    }
}

